﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP80
{
    /// <summary>
    /// 动作编号1
    /// 焊液爬升结果
    /// 配置点已修改为通用采集，不会执行此类
    /// </summary>
    public class DB3031_Work01Action : OP80ActionBase
    {
        public DB3031_Work01Action(DecodeValue _value) : base(_value)
        {
        }
        public override void Execute()
        {
            var replayDB = 3030;
            var replayAction = 10;
            var result = Value.Value.ToInt();
            
            var replayPos = Value.GetPosition(replayDB, replayAction, 0);
            
            if (result == 1)
            {
                string coverCode = Value.GetLinkData(1).ToString(); //盖板码
                int fixtureId = Value.GetLinkData(2).ToInt(); // 夹具编号
                var DetectionResults = Value.GetLinkData(3).Adapt<List<int>>(); //8个相机检测结果
                var fixtures = db.Queryable<CksFixtureinfo>().Where(a => a.FixtureId == fixtureId).ToList();
                // 保存数据到钎焊记录 查询最新的一条工装钎焊记录
                // DC_OP80ProductRecord
                var one  = db.Queryable<DcOp80Record>().Where(a=>a.FixtureId == fixtureId).OrderByDescending(a=>a.Id).First();
                if(one != null && one.FlatnessCheckResult == 1 && one.BrazingTime == null )
                {
                    one.CoverCode = coverCode;
                    one.BrazingTime = DateTime.Now;
                    one.InspectionResult1 = Value.GetLinkData(3).ToInt();
                    one.InspectionResult2 = Value.GetLinkData(4).ToInt();
                    one.InspectionResult3 = Value.GetLinkData(5).ToInt();
                    one.InspectionResult4 = Value.GetLinkData(6).ToInt();
                    one.InspectionResult5 = Value.GetLinkData(7).ToInt();
                    one.InspectionResult6 = Value.GetLinkData(8).ToInt();
                    one.InspectionResult7 = Value.GetLinkData(9).ToInt();
                    one.InspectionResult8 = Value.GetLinkData(10).ToInt();

                    //for (int i = 0; i < DetectionResults.Count; i++) {
                    //    int No = i + 1;
                    //    one.SetPropertyValue($"InspectionResult{No}", DetectionResults[i]);

                    //}
                    db.Updateable(one).ExecuteCommand();
                }
                EventBus.AddLog($"OP80请求保存-焊液爬升夹具号 {fixtureId}");
                AckWriteInt16(replayPos, 1);
            }
            else
            {
              
                AckWriteInt16(replayPos, 0);
                logger.LogInformation($"OP80请求保存-焊液爬升-信号重置");
            }
        }
    }
}
